package com.liliudong.keelflower.upms.admin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.liliudong.keelflower.common.core.utils.R;
import com.liliudong.keelflower.upms.biz.entity.sys.SysUser;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
 * @author Liudong.li
 */
@RequiredArgsConstructor
public abstract class BaseController<T extends IService<M>, M> {

    protected final T service;

    /**
     * 新增一个
     *
     * @param m
     * @return
     */
    @ApiOperation(value = "新增")
    @PostMapping("/add")
    public R<?> add(@RequestBody M m) {
        service.save(m);
        return R.success();
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据主键删除")
    @GetMapping("/del/{id}")
    public R<?> del(@PathVariable Long id) {
        service.removeById(id);
        return R.success();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "批量删除")
    @PostMapping("/delBatch")
    public R<?> delBatch(@RequestBody List<Long> ids) {
        service.removeByIds(ids);
        return R.success();
    }

    /**
     * 更新
     *
     * @param m
     * @return
     */
    @ApiOperation(value = "更新")
    @PostMapping("/update")
    public R<?> update(@RequestBody M m) {
        service.updateById(m);
        return R.success();
    }

    /**
     * 分页查询
     *
     * @param pageCurrent
     * @param pageSize
     * @param m
     * @return
     */
    @ApiOperation(value = "分页查询")
    @PostMapping("/page/{pageCurrent}/{pageSize}")
    public R<?> update(@PathVariable Long pageCurrent, @PathVariable Long pageSize, @RequestBody(required = false) M m) {
        Page<M> mPage = new Page<>(pageCurrent, pageSize);
        Page<M> page = service.page(mPage);
        return R.success(page);
    }

    /**
     * 查询详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据主键查询详情")
    @GetMapping("/info/{id}")
    public R<?> update(@PathVariable Long id) {
        M m = service.getById(id);
        return R.success(m);
    }

    /**
     * 获取登录用户
     *
     * @return
     */
    protected SysUser getLoginUser() {
        return (SysUser) SecurityUtils.getSubject().getPrincipal();
    }
}
